#include "ws_connection_manager.h"
#include "utils_log.h"
#include <chrono>
#include <random>

namespace El {
namespace Restful {

WebSocketConnectionManager &WebSocketConnectionManager::GetInstance()
{
    static WebSocketConnectionManager instance;
    return instance;
}

std::string WebSocketConnectionManager::ProcessEvent(std::shared_ptr<El::WebServer::WebSocketEvent> &event)
{
    EL_DEBUG("Processing WebSocket event for connection_id: {}, type: {}", event->connection_id,
              static_cast<int>(event->type));

    switch (event->type) {
        case El::WebServer::WebSocketEventType::Connect: {
            EL_INFO("New WebSocket connection established, connection_id: {}", event->connection_id);
            // 创建新的连接处理器
            auto connection_handler = CreateConnectionHandler(event->connection_id);
            return ""; // 连接建立时不需要返回消息
        }
        case El::WebServer::WebSocketEventType::Message: {
            // 获取已存在的连接处理器处理消息
            auto connection_handler = GetConnectionHandler(event->connection_id);
            if (!connection_handler) {
                EL_ERROR("No connection handler found for connection: {}", event->connection_id);
                return "";
            }
            return connection_handler->ProcessEvent(event);
        }
        case El::WebServer::WebSocketEventType::Disconnect: {
            EL_INFO("WebSocket connection closed, connection_id: {}", event->connection_id);
            // 处理连接关闭
            HandleConnectionClosed(event->connection_id);
            return ""; // 连接关闭时不需要返回消息
        }
        default:
            EL_ERROR("Unknown WebSocket event type: {}", static_cast<int>(event->type));
            return "";
    }
}

void WebSocketConnectionManager::HandleConnectionClosed(int64_t connection_id)
{
    std::lock_guard<std::mutex> lock(handlers_mutex_);
    auto it = connection_handlers_.find(connection_id);
    if (it != connection_handlers_.end()) {
        EL_INFO("Removing connection handler for connection: {}", connection_id);
        connection_handlers_.erase(it);
    }
}

std::shared_ptr<WebSocketConnection> WebSocketConnectionManager::GetConnectionHandler(int64_t connection_id)
{
    std::lock_guard<std::mutex> lock(handlers_mutex_);
    auto it = connection_handlers_.find(connection_id);
    if (it != connection_handlers_.end()) {
        return it->second;
    }
    return nullptr;
}

std::shared_ptr<WebSocketConnection> WebSocketConnectionManager::CreateConnectionHandler(int64_t connection_id)
{
    std::lock_guard<std::mutex> lock(handlers_mutex_);
    EL_INFO("Creating new connection handler for connection: {}", connection_id);
    auto handler = std::make_shared<WebSocketConnection>(connection_id);
    connection_handlers_[connection_id] = handler;
    return handler;
}

} // namespace Restful
} // namespace El
